#include "tokenizer.h"
#include <stdlib.h>


const char* token_readQuote(File* file)
{
  char c;
  char* ret = malloc(sizeof(char));
  int length = 1;
  while(!file_isEnd(file))
    {
      c = file_getc(file);
      if(c == '"')
        break;
  
      ret = realloc(ret, sizeof(char) * length);
      ret[length - 1] = c;
      length++;
    }
  ret = realloc(ret, sizeof(char) * length + 1);
  ret[length + 1] = '\0';
  return ret;
}




Token* token_readNext(File* file)
{
  Token* ret = (Token*) malloc(sizeof(Token));
  char c = file_skipSpace(file);
  char* tokenText;
  short length = 0;
  while(1)
    {
      if(file_isEnd(file))
        return NULL;
      if((c == ' ' || c == '\t' || c == '\n') && length)
        {
          break;
        }
      else if(c == ';')
        {
          file_readToEndOfLine(file);
        }
      else if(c == '"')
        {
          ret->text = token_readQuote(file);
          ret->type = TYPE_STRING;
          return ret;
        }
      else if(c != '\n' && c != '\r' && c != 0x20 )
        {
          if(!length)
            {
              tokenText = malloc(sizeof(char));
            }
          else
            {
              tokenText = realloc(tokenText, sizeof(char) * (length + 1));
            }
            tokenText[length] = c;
            length++;
        }
      c = file_getc(file);
    }
  tokenText[length] = '\0';
  ret->text = tokenText;
  if(tokenText[length - 1] == ':')
    {
      ret->type = TYPE_LABEL;
    }
  else if(tokenText[0] == '.')
    {
      ret->type = TYPE_SECTION;
    }
  else
    {
      ret->type = TYPE_SYMBOL;
    }
  return ret;
}


Token* token_tokenizeFile(File* file)
{
  Token* ret;
  Token* last = NULL;
  Token* current = token_readNext(file);
  Token* next = token_readNext(file);
  ret = current;
  while(current)
    {
      current->last = last;
      current->next = next;


      last = current;
      current = next;
      next = token_readNext(file);
    }
  return ret;
}
